import { AdminUserModel } from '~/server/models/admin_user.model';

/**
 * @api {post} /admin/user/login 后台管理员用户登录
 * @apiName 后台管理员用户登录
 * @apiGroup 后台管理员用户
 * @apiDescription 后台管理员用户登录
 *
 * @apiPermission all admin user
 *
 * @apiSampleRequest /admin/user/login
 *
 *
 * @apiBody {String} username 用户名
 * @apiBody {String} password 密码
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccess {String} token 登录成功的 token
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '登录成功',
 *   token: 'eyJpZCI6IjY4MzlkNTY4NzljYWRlOGM2YjllMzY3ZCIsImlhdCI6MTc0ODY3NDQ4MCwiZXhwIjoxNzQ5NTM4NDgwfQ'
 * }
 */
export default defineEventHandler(async (event) => {
	try {
		const { username, password } = await readBody(event);

		if (!username || !password) {
			return {
				code: 0,
				message: '用户名或密码不能为空',
			};
		}

		// 验证用户名、密码是否正确
		const findResult = await AdminUserModel.findOne({
			username,
			password: sha256(md5(password)),
		});

		if (findResult === null) {
			return {
				code: 0,
				message: '用户名或密码错误',
			};
		}

		// 生成 Token
		const token: string | undefined = await signToken(
			{ id: findResult._id, permission: findResult.permission },
			10
		);

		return {
			code: 1,
			message: '登录成功',
			token,
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
